package com.area.cth.service.impl;

import com.area.cth.mapper.UserMapper;
import com.area.cth.common.PageBean;
import com.area.cth.pojo.User;
import com.area.cth.service.UserService;
import com.area.cth.utils.Md5Util;
import com.area.cth.utils.ThreadLocalUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Map;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Autowired
    private UserMapper um;

    @Override
    public User findByUsername(String username) {
        User u = um.findByUsername(username);
        return u;
    }

    @Override
    public void register(String username, String password) {
        String md5String = Md5Util.getMD5String(password);
        um.add(username, md5String);
    }

    @Override
    public void updateAvatar(String avatar) {
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer id = (Integer) map.get("id");
        um.updateAvatar(avatar, id);
    }

    @Override
    public void update(User user) {
        user.setUpdateTime(LocalDateTime.now());
        um.update(user);
    }

    @Override
    public void updatePwd(String newpwd) {
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer id = (Integer) map.get("id");
        um.updatePwd(Md5Util.getMD5String(newpwd), id);
    }

    @Override
    public void updateBackground(String background) {
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer id = (Integer) map.get("id");
        um.updateBackground(background, id);
    }

    @Override
    public void login(String username) {
        LocalDateTime loginTime = LocalDateTime.now();
        um.login(username, loginTime);
    }

    @Override
    public User getUserInfoById(Integer id) {
        User u = um.getUserInfoById(id);
        return u;
    }

    @Override
    public PageBean<User> getUsers(Integer pageNo, Integer pageSize, String keyword) {
        Page<User> page=Page.of(pageNo, pageSize);
        Page<User> p=lambdaQuery()
                .like(keyword!=null, User::getUsername,keyword)
                .page(page);
        PageBean<User> pb=new PageBean<>();
        pb.setTotal(p.getTotal());
        pb.setPages(p.getPages());
        pb.setRecords(p.getRecords());
        return pb;
    }
}
